const { exec } = require('../db/mysql')
const TABLE = 'tp_candidate'
const VOTER = 'tp_voter'
const VOTE = 'tp_vote'

/**
 * 获取投票列表
 * @param {string} sign
 */
const getVoteList = async (sign) => {
  sign = sign === 'personal' ? 0 : 1
  const sql = `select
    id, name, sex, birth, nation, political, education, work_time, job, technical_post, reward, situation, resume,unit, image, story, classify
    from ${TABLE} ${sign === 1 ? 'where sign=1' : ''}`
  return await exec(sql)
}

/**
 * 投票
 * @param {object} params
 */
const putVote = async (params) => {
  let voteArr = params.ids.map(d => d.id)
  const sql = `update ${TABLE} set ${params.sign} = ${params.sign}+1 where id in (${voteArr})`
  return await exec(sql)
}

/**
 * @param {object} params
 */
const insetVoterRecord = async (params) => {
  let sign = params.sign, account = params.account
  let sql = `insert into ${VOTER} (account, status) value ('${account}', '${sign}')`
  return await exec(sql)
}

/**
 * 投票记录
 * @param {object} params
 * @param {string} account
 */
const insetVoteRecord = async (params, account) => {
  let time = Date.now()
  let sign = params.sign === 'personal' ? '先进个人' : '师德标兵'
  let nameArr = params.ids.map(d => d.name).join(',')
  const sql = `insert into ${VOTE} (name, prize_name, account, time) value ('${nameArr}', '${sign}', '${account}', ${time})`
  return await exec(sql)
}

/**
 * 获取投票进度
 * @param {string} sign
 */
const getVoteInfo = async (sign) => {
  const sql = `select id, name, unit, image, story, ${sign} as num from ${TABLE} ${sign === 'pacesetter' ? 'where sign=1' : ''}`
  console.log(sql)
  return await exec(sql)
}

/**
 * 检查是否投过票
 * @param {string} account
 */
const checkVote = async (account) => {
  account = escape(account)
  const sql = `select status from ${VOTER} where account=${account}`
  return await exec(sql)
}

/**
 * 测试投票
 * @param {number} id
 * @param {string} sign
 */
// const getTestVote = async (id, sign) => {
//   const sql = `select ${sign} from ${TABLE} where id=${id}`
//   return await exec(sql)
// }

module.exports = {
  getVoteList,
  putVote,
  getVoteInfo,
  insetVoterRecord,
  insetVoteRecord,
  checkVote
}
